﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using System.Reflection;

namespace TerminationCall.Editor.Controls {
    public partial class PropertyInfoView : UserControl {

        private object _valueObject;
        private PropertyInfo _propertyInfo;

        public PropertyInfoView(PropertyInfo propertyInfo, object valueObject) {
            InitializeComponent();

            _valueObject = valueObject;
            _propertyInfo = propertyInfo;
            
            if (_propertyInfo.PropertyType == typeof(int)) {
                CreateIntControl();
            } else if (_propertyInfo.PropertyType == typeof(bool)) {
                CreateBoolControl();
            }
        }

        private void CreateIntControl() {

            Label label = new Label();
            label.AutoSize = true;
            label.Text = _propertyInfo.Name;
            label.Top = 2;

            Controls.Add(label);

            TextBox textBox = new TextBox();
            textBox.Left = label.Size.Width + 5;
            textBox.Text = _propertyInfo.GetValue(_valueObject, null).ToString();
            textBox.TextChanged += new EventHandler(textBox_TextChanged);

            Controls.Add(textBox);

            this.Width = label.Size.Width + 5 + textBox.Width;

        }

        private void CreateBoolControl() {

            CheckBox checkBox = new CheckBox();
            checkBox.AutoSize = true;
            checkBox.Text = _propertyInfo.Name;
            checkBox.Checked = Convert.ToBoolean(_propertyInfo.GetValue(_valueObject, null));
            checkBox.Top = 2;
            checkBox.CheckedChanged += new EventHandler(checkBox_CheckedChanged);

            Controls.Add(checkBox);

            this.Width = checkBox.Width;
        }

        void checkBox_CheckedChanged(object sender, EventArgs e) {
            _propertyInfo.SetValue(_valueObject, ((CheckBox)sender).Checked, null);
        }

        void textBox_TextChanged(object sender, EventArgs e) {
            _propertyInfo.SetValue(_valueObject, Convert.ToInt32(((TextBox)sender).Text), null);
        }

    }
}
